package com.sgb.alimaplibrary;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Point;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.LifecycleOwner;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.Projection;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.sgb.alimaplibrary.entity.PoiOverlay;
import com.sgb.alimaplibrary.util.SensorEventHelper;
import com.swgk.core.util.MToast;

import java.util.ArrayList;
import java.util.List;

/**
 * 地图Marker实现
 */
public class MapMarkerTools implements AMapLocationListener, LocationSource, AMap.OnMarkerClickListener, AMap.InfoWindowAdapter, IPresenter {

    private Context mActivity;

    //初始化地图控制器对象
    private AMap aMap;
    private UiSettings mUiSettings;
    private MapView mapView;
    private OnLocationChangedListener mListener;
    private AMapLocationClient mlocationClient;
    private AMapLocationClientOption mLocationOption;

    private List<LatLng> pointList = new ArrayList<>();//当前屏幕中的所有Marker的点
    private Marker centerMarker;//当前选中的Marker
    private Marker mLocMarker;//自己的定位Marker
    //    private Circle mCircle;//自定义定位图标
    private double radius;//精度园
    private SensorEventHelper mSensorHelper; //处理定位图标跟着手机转动
    private boolean mFirstFix = false;
    private LatLng centerPoint;//当前选中的Marker的点
    private LatLng locationPoint;//当前定位后的Marker的点
    public static final String LOCATION_MARKER_FLAG = "mylocation";
    private static final int STROKE_COLOR = Color.argb(0, 0, 0, 0);
    private static final int FILL_COLOR = Color.argb(0, 0, 0, 0);
    private MyLocationStyle myLocationStyle;
    private List<PoiItem> poiItems = new ArrayList<>();
    private PoiOverlay poiOverlay;
    private MapPoiTools mMapPoiTools;
    private int myIcon = 0;
    private boolean isShowLocation = false;
    private boolean isOpenLoction = true;
    private int myLocationBitmap = 0;
    private List<Marker> markers;
    private List<MarkerOptions> pickMarkers = new ArrayList<>();
    private int zoomPosition = 10; //4-40 ,值越大越详细

    /**
     * @param mActivity
     * @param lifecycle 生命周期的觀察者
     */
    public MapMarkerTools(Context mActivity, Lifecycle lifecycle) {
        this.mActivity = mActivity;
        if (lifecycle != null) {
            //和 activity 或 fragment 生命周期綁定
            lifecycle.addObserver(this);
        }
    }

    /**
     * @param mActivity
     * @param lifecycle 生命周期的觀察者
     */
    public MapMarkerTools(Context mActivity, Lifecycle lifecycle, boolean isOpenLoction) {
        this.mActivity = mActivity;
        this.isOpenLoction = isOpenLoction;
        if (lifecycle == null) {
            //和 activity 或 fragment 生命周期綁定
            lifecycle.addObserver(this);
        }
    }

    @Override
    public void onLifecycleChanged(LifecycleOwner owner, Lifecycle.Event event) {

    }

    @Override
    public void onResume() {
        Log.d(mActivity.getClass().getSimpleName() + "-TextView:", "onResumed");
        if (mapView != null) {
            mapView.onResume();
        }
        if (mSensorHelper != null) {
            mSensorHelper.registerSensorListener();
        }
    }

    @Override
    public void onPause() {
        Log.d(mActivity.getClass().getSimpleName() + "-TextView:", "onPause");
        if (mSensorHelper != null) {
            mSensorHelper.unRegisterSensorListener();
            mSensorHelper.setCurrentMarker(null);
            mSensorHelper = null;
        }
        if (mapView != null) {
            mapView.onPause();
        }
        deactivate();
        mFirstFix = false;
    }

    @Override
    public void onDestroy() {
        deactivate();
        if (mapView != null) {
            mapView.onDestroy();
        }
    }

    /**
     * 地图初始化
     *
     * @param savedInstanceState
     */
    public void init(Bundle savedInstanceState, MapView mMapView) {
        this.mapView = mMapView;
        mapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mMapView.getMap();
            mUiSettings = aMap.getUiSettings();
            mSensorHelper = new SensorEventHelper(mActivity);
            if (mSensorHelper != null) {
                mSensorHelper.registerSensorListener();
            }
        }
        setUpMap();
    }

    /**
     * 地图初始化
     *
     * @param savedInstanceState
     */
    public void init(Bundle savedInstanceState, MapView mMapView, int zoomPosition) {
        this.zoomPosition = zoomPosition;
        init(savedInstanceState, mMapView);
    }

    public void setMapLocationStyle(boolean isShowLocation) {
        this.isShowLocation = isShowLocation;
    }

    public void setMapLocationStyleBitmap(int myLocationBitmap) {
        this.myLocationBitmap = myLocationBitmap;
    }

    public void setMapLocationStyle(int icon) {
        myLocationStyle = new MyLocationStyle();
        Bitmap bMap = BitmapFactory.decodeResource(mActivity.getResources(), icon);
        BitmapDescriptor des = BitmapDescriptorFactory.fromBitmap(bMap);
        myLocationStyle.myLocationIcon(des);// 设置小蓝点的图标
        myLocationStyle.showMyLocation(true);//设置是否显示定位小蓝点，用于满足只想使用定位，不想使用定位小蓝点的场景，设置false以后图面上不再有定位蓝点的概念，但是会持续回调位置信息。

//        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
//        myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//连续定位、蓝点不会移动到地图中心点，地图依照设备方向旋转，并且蓝点会跟随设备移动。
    }

    /**
     * 设置一些amap的属性
     */
    private void setUpMap() {
        // 自定义系统定位小蓝点
        if (myLocationStyle == null) {
            if (myLocationBitmap == 0) {
                myLocationBitmap = R.drawable.navi_map_gps_locked;
            }
            setMapLocationStyle(myLocationBitmap);
        }
//        myLocationStyle.strokeColor(Color.WHITE);//设置定位蓝点精度圆圈的边框颜色的方法。
//        myLocationStyle.radiusFillColor(Color.argb(0,0,0,0));// 设置定位蓝点精度圆圈的填充颜色的方法。
//        myLocationStyle.strokeWidth(0.1f);// 设置定位蓝点精度圈的边框宽度的方法。
        aMap.setMyLocationStyle(myLocationStyle);
        aMap.setLocationSource(this);// 设置定位监听
        aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setMyLocationType(MyLocationStyle.LOCATION_TYPE_LOCATE);//定位模式
        aMap.setOnMarkerClickListener(this); //Marker的点击事件
        aMap.setInfoWindowAdapter(this);
        mUiSettings.setZoomPosition(zoomPosition);
        mUiSettings.setZoomControlsEnabled(false);//缩放按钮是否显示
        mUiSettings.setMyLocationButtonEnabled(isShowLocation);// 设置默认定位按钮是否显示
    }

    public void setMapClick() {
        aMap.setOnMapClickListener(new AMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {
                aMap.clear();
                BitmapDescriptor bitmapSmall = BitmapDescriptorFactory.fromResource(R.drawable.marker_big);
                MarkerOptions markerOption = new MarkerOptions()
                        .position(latLng)
                        .title("选定位置")
                        .icon(bitmapSmall)
                        .draggable(false);
                aMap.addMarker(markerOption);
                if (mMapPoiTools == null) {
                    mMapPoiTools = MapPoiTools.newInstance(mActivity, aMap, new MapPoiTools.CalllBack() {
                        @Override
                        public void onRegeocodeSearched(String suggestionCityList) {
                            if (click != null) {
                                click.getAddress(latLng.latitude, latLng.longitude, suggestionCityList);
                            }
                        }
                    });
                }
                mMapPoiTools.latlotSearchQuery(latLng);
            }
        });
    }

    //根据中心点和自定义内容获取缩放bounds
    private LatLngBounds getLatLngBounds(LatLng centerpoint, List<LatLng> pointList) {
        LatLngBounds.Builder b = LatLngBounds.builder();
        if (centerpoint != null) {
            if (aMap.getMapScreenMarkers().size() > pointList.size()) {
                for (int i = 0; i < aMap.getMapScreenMarkers().size(); i++) {
                    LatLng p = aMap.getMapScreenMarkers().get(i).getPosition();
                    LatLng p1 = new LatLng((centerpoint.latitude * 2) - p.latitude, (centerpoint.longitude * 2) - p.longitude);
                    b.include(p);
                    b.include(p1);
                }
                return b.build();
            }
            for (int i = 0; i < pointList.size(); i++) {
                LatLng p = pointList.get(i);
                LatLng p1 = new LatLng((centerpoint.latitude * 2) - p.latitude, (centerpoint.longitude * 2) - p.longitude);
                b.include(p);
                b.include(p1);
            }
        }
        return b.build();
    }

    public void startLocation() {
        if (mlocationClient != null) {
            mlocationClient.startLocation();
        }
    }

    public MarkerClick click;

    public void onSaveInstanceState(Bundle outState) {
        if (mapView != null) {
            mapView.onSaveInstanceState(outState);
        }
    }

    /**
     * 定制展示marker信息的View
     *
     * @param marker
     * @return
     */
    @Override
    public View getInfoWindow(Marker marker) {
        View infoWindow = null;
        if (infoWindow == null) {
            infoWindow = LayoutInflater.from(mActivity).inflate(
                    R.layout.custom_info_window, null);
        }
        infoWindow.setBackground(mActivity.getResources().getDrawable(android.R.color.transparent));
        return infoWindow;
    }

    /**
     * 提定制展示marker信息的View。
     *
     * @param marker
     * @return
     */
    @Override
    public View getInfoContents(Marker marker) {
        View infoWindow = null;
        if (infoWindow == null) {
            infoWindow = LayoutInflater.from(mActivity).inflate(
                    R.layout.custom_info_window, null);
        }
        infoWindow.setBackground(mActivity.getResources().getDrawable(android.R.color.transparent));
        return infoWindow;
    }

    public abstract static class MarkerClick {
        /**
         * 绘制在地图上的Marker点击回调
         *
         * @param pos
         * @param title
         */
        public abstract void onMarkerClick(int pos, String title);

        public void onMarkerClick(int pos, String title, Marker marker) {
        }

        /**
         * 这里开启的是多次定位，当定位成功会一直返回，故会多次调用，使用此方法一定多注意
         *
         * @param currentLat
         * @param currentLong
         */
        public abstract void onLocationChanged(Double currentLat, Double currentLong, String address);

        public void getAddress(Double Lat, Double Log, String address) {
        }

        public void failure() {
        }
    }

    public void setMarkerClick(MarkerClick click) {
        this.click = click;
    }

    /**
     * 对marker标注点点击响应事件
     */
    @Override
    public boolean onMarkerClick(final Marker marker) {
        if (aMap != null) {
            if (LOCATION_MARKER_FLAG.equals(marker.getTitle())) return true;
            if (marker.getPosition() == locationPoint) return true;
            centerMarker = marker;
            centerPoint = marker.getPosition();
            try {
                if (click != null) {
                    int i = getPoiIndex(marker);
                    click.onMarkerClick(i, marker.getTitle());
                    click.onMarkerClick(i, marker.getTitle(), marker);
                }
            } catch (Exception e) {
                e.printStackTrace();
                click.onMarkerClick(0, marker.getTitle());
                click.onMarkerClick(0, marker.getTitle(), marker);
            }
//            jumpPoint(marker);
        }
        return false; //false表示marker被点击后显示在屏幕中心,true则不会.
    }

    /**
     * 在地图上添加marker
     */
    public List<PoiItem> addPoiItem(Double currentLat, Double currentLong, String title) {
        LatLonPoint latLonPoint = new LatLonPoint(currentLat, currentLong);
        poiItems.add(new PoiItem(title, latLonPoint, title, ""));
        pointList.add(new LatLng(currentLat, currentLong));
        return poiItems;
    }

    /**
     * 每次清空地图上的点重新绘制更多的点
     *
     * @param icon
     * @param isShowText
     */
    public void addAllMarkerToMap(int icon, boolean isShowText) {
        poiOverlay = new PoiOverlay(mActivity, aMap, poiItems);
        poiOverlay.removeFromMap();
        poiOverlay.addToMap(icon, isShowText);
        poiOverlay.zoomToSpan();
    }

    /**
     * 每次清空地图上的点重新绘制更多的点
     *
     * @param icon
     * @param isShowText
     */
    public void addAllMarkerToMap(int icon, boolean isShowText, List<PoiItem> pois) {
        poiItems.clear();
        poiItems.addAll(pois);
        poiOverlay = new PoiOverlay(mActivity, aMap, poiItems);
        poiOverlay.removeFromMap();
        poiOverlay.addToMap(icon, isShowText);
        poiOverlay.zoomToSpan();
    }

    /**
     * 每次清空地图上的点重新绘制更多的点
     *
     * @param icon
     * @param isShowText
     */
    public void addAllMarkerToMap(int icon, boolean isShowText, List<PoiItem> pois, LatLng locationPoint) {
        this.locationPoint = locationPoint;
        poiItems.clear();
        poiItems.addAll(pois);
        poiOverlay = new PoiOverlay(mActivity, aMap, poiItems);
        poiOverlay.removeFromMap();
        poiOverlay.addToMap(icon, isShowText);
        poiOverlay.zoomToSpan();
    }

    public void addAllMarker(List<MarkerOptions> markerOptionsList) {
        for (MarkerOptions markerOptions : markerOptionsList) {
            aMap.addMarker(markerOptions);
        }
    }

    /**
     * 清空地图上的，marker 标记，然后重新添加
     *
     * @param markerEntityList
     */
    public List<PoiItem> setPoiItem(List<MarkerEntity> markerEntityList) {
        List<PoiItem> poiItems = new ArrayList<>();
        for (MarkerEntity markerEntity : markerEntityList) {
            LatLonPoint latLonPoint = new LatLonPoint(markerEntity.getLatLng().latitude, markerEntity.getLatLng().longitude);
            poiItems.add(new PoiItem(markerEntity.getTitle(), latLonPoint, markerEntity.getTitle(), ""));
        }
        return poiItems;
    }

    /**
     * 将标记的经纬度集合转换为地图可识别标点
     *
     * @param markerEntityList
     * @return
     */
    private List<MarkerOptions> getMarkerOptions(List<MarkerEntity> markerEntityList) {
        List<MarkerOptions> markerOptionsList = new ArrayList<>();
        for (MarkerEntity markerEntity : markerEntityList) {
            markerOptionsList.add(getMarkerOptions(markerEntity));
        }
        return markerOptionsList;
    }

    public void setData(List<MarkerOptions> markerOptionsList, boolean isShowLocation) {
        if (isShowLocation) {
            mapClear();
        } else {
            aMap.clear();
        }
        addAllMarker(markerOptionsList);

    }

    public void setDataPick(List<MarkerEntity> markerEntityList, boolean isShowLocation,LatLng latLng) {
        if(markerEntityList == null){
            mapClear();
            return;
        }
        if (isShowLocation) {
            mapClear();
        } else {
            aMap.clear();
            pickMarkers.clear();
        }
        for (MarkerEntity markerEntity : markerEntityList) {
            MarkerOptions markerOptions = getMarkerOptions(markerEntity);
            aMap.addMarker(markerOptions);
            pickMarkers.add(markerOptions);
//            if(markerEntity.getLatLng().equals(latLng)){
//                zoomToSpan(latLng);
//            }
        }
        zoomToSpan(latLng);
    }

    /**
     * 移动镜头到当前的视角。
     *
     * @since V2.1.0
     */
    public void zoomToSpan() {
        try {
            if (aMap == null)
                return;
            markers = aMap.getMapScreenMarkers();
            if (markers.size() == 1) {
                aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(markers.get(0).getPosition().latitude,
                        markers.get(0).getPosition().longitude), 18f));
            } else {
                LatLngBounds bounds = getLatLngBounds();
                aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));
            }
            aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    /**
     * 移动到当前经纬度视图
     *
     * @param latLng
     */
    public void zoomToSpan(LatLng latLng) {
        if (aMap == null)
            return;
        markers = aMap.getMapScreenMarkers();
        List<LatLng> pointList = new ArrayList<>();
        pointList.add(latLng);
        LatLngBounds bounds = getLatLngBounds(latLng, pointList);
        aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 50));
        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));
    }

    /**
     * 移动指定经纬度位置，设定缩放比例
     *
     * @param latLng
     * @param zoom
     */
    public void mapMoveCamera(LatLng latLng, float zoom) {
        if (aMap == null) {
            return;
        }
        aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, zoom));
    }


    public List<Marker> getMapScreenMarkers() {
        return aMap.getMapScreenMarkers();
    }

    public List<MarkerOptions> getMapMarkersPick() {
        return pickMarkers;
    }

    private LatLngBounds getLatLngBounds() {
        LatLngBounds.Builder b = LatLngBounds.builder();
        for (int i = 0; i < markers.size(); i++) {
            b.include(new LatLng(markers.get(i).getPosition().latitude,
                    markers.get(i).getPosition().longitude));
        }
        return b.build();
    }

    public MarkerOptions getMarkerOptions(MarkerEntity markerEntity) {
        BitmapDescriptor bitmapSmall;
        if (markerEntity.getIcon() == 0 && markerEntity.getView() != null) {
            bitmapSmall = BitmapDescriptorFactory.fromView(markerEntity.getView());
        } else {
            bitmapSmall = BitmapDescriptorFactory.fromResource(markerEntity.getIcon());
        }
        MarkerOptions markerOption = new MarkerOptions()
                .position(markerEntity.getLatLng())
                .title(markerEntity.getTitle())
//                .snippet(markerEntity.getSnippet())
                .icon(bitmapSmall)
                .draggable(false);
        return markerOption;
    }

    /**
     * 获取当前marker在整个marker数组中的位置
     *
     * @param marker
     * @return
     */
    public int getPoiIndex(Marker marker) {
        int i = -1;
        for (Marker marker1 : aMap.getMapScreenMarkers()) {
            String title = TextUtils.isEmpty(marker1.getTitle()) ? "" : marker1.getTitle();
            if (title.equals(marker.getTitle())) {
                return i;
            }
            i++;
        }
        return i;
    }

    /**
     * marker点击时跳动一下
     */
    public void jumpPoint(final Marker marker) {
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        Projection proj = aMap.getProjection();
        final LatLng markerLatlng = marker.getPosition();
        Point markerPoint = proj.toScreenLocation(markerLatlng);
        markerPoint.offset(0, -100);
        final LatLng startLatLng = proj.fromScreenLocation(markerPoint);
        final long duration = 1500;

        final Interpolator interpolator = new BounceInterpolator();
        handler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;
                float t = interpolator.getInterpolation((float) elapsed
                        / duration);
                double lng = t * markerLatlng.longitude + (1 - t)
                        * startLatLng.longitude;
                double lat = t * markerLatlng.latitude + (1 - t)
                        * startLatLng.latitude;
                marker.setPosition(new LatLng(lat, lng));
                if (t < 1.0) {
                    handler.postDelayed(this, 16);
                }
            }
        });
    }

    public void addLocationMarker() {
        if (locationPoint == null) return;
        if (!mFirstFix) {
            mFirstFix = true;
            centerPoint = new LatLng(locationPoint.latitude, locationPoint.longitude);
            addCircle(locationPoint, radius);//添加定位精度圆
            addMarker(locationPoint);//添加定位图标
            if (mSensorHelper != null) {
                mSensorHelper.setCurrentMarker(mLocMarker);//定位图标旋转
            }
        } else {
//            mCircle.setCenter(locationPoint);
//            mCircle.setRadius(radius);
            mLocMarker.setPosition(locationPoint);
//            if (!aMap.getMapScreenMarkers().contains(mLocMarker)){
//                deactivate();
//                onResume();
//            }
        }
    }

    public void mapClear() {
        aMap.clear();
        pointList.clear();
        poiItems.clear();
        mLocMarker = null;
        mFirstFix = false;
        if (locationPoint == null) return;
        addLocationMarker();
    }

    public void setMyLocation(Double currentLat, Double currentLong) {
        deactivate();
        aMap.clear();
        pointList.clear();
        poiItems.clear();
        mLocMarker = null;
        mFirstFix = false;
        locationPoint = new LatLng(currentLat, currentLong);
        addPoiItem(currentLat, currentLong, "");
        addAllMarkerToMap(myIcon, false);
        LatLngBounds bounds = getLatLngBounds(locationPoint, pointList);
        aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 18));
    }

    public void setMyLocation(Double currentLat, Double currentLong, int myIcon) {
        this.myIcon = myIcon;
        setMyLocation(currentLat, currentLong);
    }

    /**
     * 定位成功后回调函数
     */
    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation != null
                    && amapLocation.getErrorCode() == 0) {
//                MToast.showLongToast(mActivity,"定位成功");
                locationPoint = new LatLng(amapLocation.getLatitude(), amapLocation.getLongitude());
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点
                radius = amapLocation.getAccuracy();

                if (!mFirstFix) {
                    LatLngBounds bounds = getLatLngBounds(locationPoint, pointList);
                    aMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bounds, 14));
                    mFirstFix = true;
                } else {
                    addLocationMarker();
                }
                if (click != null) {
                    click.onLocationChanged(locationPoint.latitude, locationPoint.longitude, amapLocation.getAddress());
                }
            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
                try {
//                    MToast.showLongToast(mActivity, "定位失败");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (click != null) {
                    click.failure();
                }
            }
        }
    }

    /**
     * 激活定位
     */
    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            mlocationClient = new AMapLocationClient(mActivity);
            mLocationOption = new AMapLocationClientOption();
            //设置定位监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            if (isOpenLoction) {
                mlocationClient.startLocation();
            }
        }
    }

    /**
     * 停止定位
     */
    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    private void addCircle(LatLng latlng, double radius) {
//        pointList.add(latlng);
//        CircleOptions options = new CircleOptions();
//        options.strokeWidth(1f);
//        options.fillColor(FILL_COLOR);
//        options.strokeColor(STROKE_COLOR);
//        options.center(latlng);
//        options.radius(radius);
//        mCircle = aMap.addCircle(options);
    }

    private void addMarker(LatLng latlng) {
        if (mLocMarker != null) {
            return;
        }

        Bitmap bMap = BitmapFactory.decodeResource(mActivity.getResources(), R.drawable.location);
        if (myLocationBitmap != 0) {
            bMap = BitmapFactory.decodeResource(mActivity.getResources(), R.drawable.location_red);
        }

        BitmapDescriptor des = BitmapDescriptorFactory.fromBitmap(bMap);

//		BitmapDescriptor des = BitmapDescriptorFactory.fromResource(R.drawable.navi_map_gps_locked);
        MarkerOptions options = new MarkerOptions();
        options.icon(des);
        options.anchor(0.5f, 0.5f);
        options.position(latlng);
        options.title(LOCATION_MARKER_FLAG);
        mLocMarker = aMap.addMarker(options);
    }

}

